var http_ok = "200";

//自定义扩展jQuery方法
$.fn.serializeJson=function(){
    var serializeObj={};
    var array=this.serializeArray();
    // var str=this.serialize();
    $(array).each(function(){ // 遍历数组的每个元素
        if(serializeObj[this.name]){ // 判断对象中是否已经存在 name，如果存在name
            if($.isArray(serializeObj[this.name])){
                serializeObj[this.name].push(this.value); // 追加一个值 hobby : ['音乐','体育']
            }else{
                // 将元素变为 数组 ，hobby : ['音乐','体育']
                serializeObj[this.name]=[serializeObj[this.name],this.value];
            }
        }else{
            serializeObj[this.name]=this.value; // 如果元素name不存在，添加一个属性 name:value
        }
    });
    return serializeObj;
};

//
// $.fn.serializeJson = function () {
//     var serializeObj = {};
//     var array = this.serializeArray();
//     $.each(array, function () {
//         if (serializeObj[this.name] !== undefined) {
//             if (!serializeObj[this.name].push) {
//                 serializeObj[this.name] = [serializeObj[this.name]];
//             }
//             serializeObj[this.name].push(this.value || '');
//         } else {
//             serializeObj[this.name] = this.value || '';
//         }
//     });
//     return serializeObj;
// };



//获取url中的参数
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

$.postJSON = function (url, data, callback) {
    return $.ajax({
        type: "post", //请求方式设置为post
        url, //要请求的url地址
        data: JSON.stringify(data), //传入的数据 转换为json对象
        headers: {
            "Content-Type": "application/json",
        },//设置请求头
        success: callback//传入成功后的请求回调
    });
};


function formAuthAjax(url, data) {
    const cookie = $.cookie('loginAuth');
    var resultData = {};
    var indexLoad ;
    $.ajax({
        type: "post", //请求方式设置为post
        url: url, //要请求的url地址
        data: data, //传入的数据 转换为json对象
        async: false,
        contentType: false, //jax 中 contentType 设置为 false 是为了避免 JQuery 对其操作，从而失去分界符，而使服务器不能正常解析文件
        processData: false, //当设置为true的时候,jquery ajax 提交的时候不会序列化 data，而是直接使用data
        headers: {
            "token": cookie
        },//设置请求头
        success: function (result) {
            const code = result.code;
            if (code === '401') {
                window.location = "/login-2.html"
            }
            if (code !== '200') {
                layer.msg(result.msg, {icon: 2, time: 3000, title: '请求失败'});
            }

            if (code === '200') {
                layer.msg('请求成功', {icon: 1, time: 3000});
            }

            resultData = result;
        },//传入成功后的请求回调
        beforeSend :function () {
            indexLoad = layer.load(1);
        },//请求之前调用
        error: function(data){
            layer.close(indexLoad);
        },
        beforeSend: function () {
            layer.close(indexLoad);
        }
    });

    return resultData;
}
function downloadFile(fileUrl) {
    // 创建一个a标签
    var a = document.createElement('a');
    a.href = fileUrl;
    a.setAttribute('download', ''); // 可以设置下载的文件名
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

function downloadAjax(url, method, data){
    const cookie = $.cookie('loginAuth');
    var indexLoad ;
    if (method === 'post' || method === 'POST' ) {
        $.ajax({
            type: method, //请求方式设置为post
            url: url, //要请求的url地址
            data: JSON.stringify(data), //传入的数据 转换为json对象
            //定义响应类型为 blob
            xhrFields: {
                responseType: 'blob'
            },
            async: true,
            headers: {
                "Content-Type": "application/json",
                "token": cookie
            },//设置请求头
            success: function (response,status, xhr) {
                console.info(5);
                console.info(status);
                var contentDisposition = xhr.getResponseHeader('Content-Disposition');
                var blob = new Blob([response], { type: 'application/octet-stream' });// 此转换为xhrFields: { responseType: "arraybuffer" },
                var filename = contentDisposition.replace(/.*filename[^;=\n]*=((['"]).*?\2|[^;\n]*)*.*/, "$1");
                var link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.download = filename;
                document.body.appendChild(link);
                link.click()

            },//传入成功后的请求回调
            error: function () {
                alert("请求错误")
            },//传入成功后的请求回调
            beforeSend :function () {
                indexLoad = layer.load(2);
            },//请求之前调用
            error: function(data){
                layer.close(indexLoad);
            },
            beforeSend: function () {
                layer.close(indexLoad);
            }
        });
    }
    if (method === 'get' || method === 'GET' ) {
        $.ajax({
            type: method, //请求方式设置为post
            url: url, //要请求的url地址
            data: data, //传入的数据 转换为json对象
            async: false,
            headers: {
                "Content-Type": "application/json",
                "token": cookie
            },//设置请求头
            success: function (response, status) {
                var blob = new Blob([response], { type: "application/pdf" });// 此转换为xhrFields: { responseType: "arraybuffer" },

                var link = document.createElement("a");
                link.href = window.URL.createObjectURL(response);
                link.download = "example.pdf";
                document.body.appendChild(link);
                link.click();
            },//传入成功后的请求回调
            dataType: "json",
            error: function () {
                alert("请求错误")
            },//传入成功后的请求回调
            beforeSend :function () {
                indexLoad = layer.load(2);
            },//请求之前调用
            error: function(data){
                layer.close(indexLoad);
            },
            beforeSend: function () {
                layer.close(indexLoad);
            }
        });
    }
}

function JSONAuthAjax(url, method, data) {
    const cookie = $.cookie('loginAuth');
    var resultData = {};
    var indexLoad ;
    if (method === 'post' || method === 'POST' || method === 'DELETE') {
        $.ajax({
            type: method, //请求方式设置为post
            url: url, //要请求的url地址
            data: JSON.stringify(data), //传入的数据 转换为json对象
            async: false,
            dataType: "json",
            headers: {
                "Content-Type": 'application/json',
                "token": cookie
            },//设置请求头
            success: function (result) {
                const code = result.code;
                if (code === '401') {
                    window.location = "/login-2.html"
                }
                if (code !== '200') {
                    layer.msg(result.msg, {icon: 2, time: 3000, title: '请求失败'});
                }

                if (code === '200') {
                    layer.msg('请求成功', {icon: 1, time: 3000});
                }

                resultData = result;
            },//传入成功后的请求回调
            beforeSend :function () {
                indexLoad = layer.load(2);
            },//请求之前调用
            error: function(data){
                layer.close(indexLoad);
            },
            beforeSend: function () {
                layer.close(indexLoad);
            }
        });
    }
    if (method === 'get' || method === 'GET' ) {
        $.ajax({
            type: method, //请求方式设置为post
            url: url, //要请求的url地址
            data: data, //传入的数据 转换为json对象
            async: false,
            headers: {
                "Content-Type": "application/json",
                "token": cookie
            },//设置请求头
            success: function (result) {
                const code = result.code;
                if (code === '401') {
                    window.location = "/login-2.html"
                }
                if (code !== '200') {
                    layer.msg(result.msg, {icon: 2, time: 3000, title: '请求失败'});
                } else {
                    layer.msg('请求成功', {icon: 1, time: 3000, title: '请求'});
                }

                resultData = result;
            },//传入成功后的请求回调
            dataType: "json",
            error: function () {
                alert("请求错误")
            },//传入成功后的请求回调
            beforeSend :function () {
                indexLoad = layer.load(2);
            },//请求之前调用
            error: function(data){
                layer.close(indexLoad);
            },
            beforeSend: function () {
                layer.close(indexLoad);
            }
        });
    }
    return resultData;
};


function lay_tishi(data) {
    layer.open({
        title: '提示'
        , content: data
    });
}


function lay_msg(data) {
    layer.msg(data, {icon: 2, time: 3000});
}

//获取所有选中的节点id
function getLayTreeCheckedId(data) {
    var arrId = [];
    getCheckedId(data, arrId);
    return arrId;
}

//获取所有eletree选中的节点id
function getEleTreeCheckedId(data) {
    var arrId = [];
    for (var i = 0; i < data.length; i++) {
        arrId.push(data[i].id);
    }
    return arrId;
}

function getCheckedId(jsonObj, arrId) {
    jsonObj.forEach((item, index) => {
        arrId.push(item.id)
        if (item.children != []) {
            getCheckedId(item.children, arrId);//递归实现遍历每一层级数据
        }
    });
    return arrId;
}

//设置layui-table 复选框只能单选
function tableCheckBoxOnly(obj, tableArray) {
    //清除所有选框
    $("tr").find('input:checkbox').each(function () {
        $(this).prop('checked',false);
    });
    $(".layui-form-checkbox").each(function () {
        $(this).removeClass('layui-form-checked');
    });

    for(var i=0; i<tableArray.length; i++){
        tableArray[i].LAY_CHECKED = false;
    }

    //添加选框
    if(obj.index !== undefined){
        tableArray[obj.index].LAY_CHECKED = true;
        $('tr[data-index=' + obj.index + ']').find('input:checkbox:last').prop("checked",true);
        $('tr[data-index=' + obj.index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
    }

}

var dl_coder_url = {
    "login": "/system-api/auth/login",
    "show_blog_table_img": "/system-api/blogArticle/getTableImg",
    "upload_article_file": "/system-api/blogArticle/uploadImg",
    "loginOut": ["/system-api/auth/loginOut", "GET"],
    "menu": ["/system-api/system/getAllMenu", "GET"],
    "system_role": ["/system-api/system/getRoleList", "POST"],
    "resourceMenu": ["/system-api/system/getResourceMenu", "GET"],
    "update_menu": ["/system-api/system/updateResourceMenu", "POST"],
    "add_menu": ["/system-api/system/addResourceMenu", "POST"],
    "delete_menu": ["/system-api/system/deleteResourceMenu", "GET"],
    "get_role_menu": ["/system-api/system/getRoleResourceTree", "GET"],
    "save_role_menu": ["/system-api/system/saveRoleResourceTree", "POST"],
    "system_user": ["/system-api/system/getUserList", "POST"],
    "system_role_all": ["/system-api/system/getRoleListAll", "GET"],
    "add_role": ["/system-api/system/addRole", "POST"],
    "update_role": ["/system-api/system/updateRole", "POST"],
    "delete_role": ["/system-api/system/deleteRole", "GET"],
    "update_user_role": ["/system-api/system/addUpdateUserRole", "POST"],
    "add_user": ["/system-api/system/addUser", "POST"],
    "update_user": ["/system-api/system/updateUser", "POST"],
    "delete_user": ["/system-api/system/deleteUser", "GET"],
    "child_authority": ["/system-api/system/getMenuAuthorityByCode", "GET"],
    "add_sort": ["/system-api/blogSort/addBlogSort", "POST"],
    "sort_page": ["/system-api/blogSort/pageBlogSort", "POST"],
    "edit_sort": ["/system-api/blogSort/updateBlogSort", "POST"],
    "delete_sort": ["/system-api/blogSort/deleteBlogSort", "DELETE"],
    "get_shouye_info": ["/system-api/system/getShouyeInfo", "GET"],
    "save_shouye_info": ["/system-api/system/saveShouyeInfo", "POST"],
    "cloud_tag_page": ["/system-api/blogCloudTag/pageBlogTag", "POST"],
    "add_cloud_tag": ["/system-api/blogCloudTag/addBlogTag", "POST"],
    "edit_cloud_tag": ["/system-api/blogCloudTag/updateBlogTag", "POST"],
    "delete_cloud_tag": ["/system-api/blogCloudTag/deleteBlogTag", "GET"],
    "article_page": ["/system-api/blogArticle/pageBlogArticle", "POST"],
    "edit_article": ["/system-api/blogArticle/updateBlogArticle", "POST"],
    "add_article": ["/system-api/blogArticle/addBlogArticle", "POST"],
    "delete_article": ["/system-api/blogArticle/deleteBlogArticle", "DELETE"],
    "list_blogTag": ["/system-api/blogCloudTag/listBlogTag", "GET"],
    "list_blogSort": ["/system-api/blogSort/listBlogSort", "GET"],
    "info_blogArticle": ["/system-api/blogArticle/getBlogArticleInfo", "GET"],
    "blog_uploadImg": ["/system-api/blogArticle/uploadImgBlog", "POST", "file"],
    "info_blog_me": ["/system-api/blogArticle/getMeContentInfo", "GET"],
    "info_blog_me_save": ["/system-api/blogArticle/saveMeContentInfo", "POST"],
    "update_article_status": ["/system-api/blogArticle/updateBlogArticleStatus", "POST"],
    //工具
    "tool_card_front": ["/system-api/card/createIdcardFront", "POST"],
    "tool_card_back": ["/system-api/card/createIdcardBack", "POST"],
    "tool_excel": ["/system-api/excel/analysisExcel", "POST"],
    //博客用户
    "blog_user_page": ["/system-api/blogUser/pageBlogUser", "POST"]

}

